package aar.test.tessocr;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.design.widget.TextInputEditText;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import aar.test.tessocr.base.BaseActivity;
import aar.test.tessocr.baseApplication.BaseApplication;
import aar.test.tessocr.db.impl.ClientInfoDaoImp;
import aar.test.tessocr.model.DialogCallback;
import aar.test.tessocr.model.LoginCabModel;
import aar.test.tessocr.model.LzyResponse;
import aar.test.tessocr.model.loginModel;
import aar.test.tessocr.utils.ConstantPara;
import aar.test.tessocr.utils.PrefUtils;
import aar.test.tessocr.utils.Urls;
import aar.test.tessocr.utils.Utils;
import clx.tessocr.ocreng.R;
import okgo.OkGo;
import okgo.model.Response;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class Login1Activity extends BaseActivity implements View.OnClickListener{


    public static final MediaType JSON=MediaType.parse("application/json; charset=utf-8");

    private Button sign_in_button;

    private EditText phonenum;

    private EditText password;

    private Toolbar toolbar;

    private Context mContext;

    private ImageView login_maxim;

    private boolean isRemember = true;

    private TextView tv_register;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login1);
        mContext=this;

        initView();
    }

    private void initView(){
        toolbar = (Toolbar) findViewById(R.id.toolbar_normal);
        setSupportActionBar(toolbar);

        login_maxim =findViewById(R.id.iv_remember);
        login_maxim.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isRemember) {
                    isRemember = false;
                    login_maxim.setImageResource(R.mipmap.neiromglan_weixuanzhong_tongyimayitiaokuan);
                } else {
                    isRemember = true;
                    login_maxim.setImageResource(R.mipmap.neironglan_tongyitiakuan);
                }
            }
        });

        sign_in_button=findViewById(R.id.sign_in_button);
        sign_in_button.setOnClickListener(this);

        phonenum=findViewById(R.id.phonenum);
        phonenum.setText(PrefUtils.getString(Login1Activity.this, "userName", ""));
        password=findViewById(R.id.password);
        password.setText(PrefUtils.getString(Login1Activity.this, "password", ""));

        tv_register=findViewById(R.id.tv_register);
        tv_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(Login1Activity.this, RegisterActivity.class));
            }
        });

        if (!phonenum.getText().toString().equals("") && !password.getText().toString().equals("")) {
            Map<String ,Object> map=new HashMap<>();
            map.put("mobile",phonenum.getText().toString());
            map.put("password",password.getText().toString());
            map.put("app",ConstantPara.EXPRESS_CABINT);

            Gson gg=new Gson();
            String json =gg.toJson(map);

            RequestBody body = RequestBody.create(JSON,json);
            OkGo.<LzyResponse<loginModel>>post(Urls.URL_LOGIN)//
                    .tag(this)//
                    .upRequestBody(body)
                    .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                    .execute(new DialogCallback<LzyResponse<loginModel>>(Login1Activity.this) {
                        @Override
                        public void onSuccess(Response<LzyResponse<loginModel>> response) {
                            loginModel loginCabModel = response.body().data;
                            PrefUtils.setString(Login1Activity.this, "userId", loginCabModel.getId());
                            BaseApplication.getIntance().setLoginBean(response.body().data);

                            /*if (null != BaseApplication.getIntance().getLoginBean().getPhoneList() && BaseApplication.getIntance().getLoginBean().getPhoneList().size() != 0) {
                                ClientInfoDaoImp.getInstance(Login1Activity.this).deleteAll();
                                for (int i = 0; i < BaseApplication.getIntance().getLoginBean().getPhoneList().size(); i++) {
                                    ClientInfoDaoImp.getInstance(Login1Activity.this).AddTelNum(BaseApplication.getIntance().getLoginBean().getPhoneList().get(i));
                                }
                            }*/
                            BaseApplication.getIntance().setLogin(true);
                            startActivity(new Intent(Login1Activity.this, MainActivity.class));
                            finish();
                        }

                        @Override
                        public void onError(Response<LzyResponse<loginModel>> response) {
                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.login_failed), Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }

    public void showImageDrawable(Integer path, ImageView imageview) {
        //图片来源于
        imageview.setImageBitmap(ReadBitMap(mContext, path));
    }


    public Bitmap ReadBitMap(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }



    @Override
    public void onClick(View v) {

        switch (v.getId()){

            case R.id.sign_in_button:
                signIn();
              break;

          default:
         break;

        }

    }






    private void signIn(){

        String phnumber=phonenum.getText().toString();

        String pass=password.getText().toString();

        if(TextUtils.isEmpty(phnumber)){

            Toast.makeText(mContext,getResources().getString(R.string.error_empty_phonenum),Toast.LENGTH_SHORT).show();

            return ;
        }

        if(11!=phnumber.length() || !Utils.isMobile(phnumber)){

            Toast.makeText(mContext,getResources().getString(R.string.error_invalid_phonenum),Toast.LENGTH_SHORT).show();

            return ;
        }


        if(TextUtils.isEmpty(pass)){
            Toast.makeText(mContext,getResources().getString(R.string.error_empty_password),Toast.LENGTH_SHORT).show();

            return ;

        }

        Map<String ,Object> map=new HashMap<>();
        map.put("mobile",phnumber);
        map.put("password",pass);
        map.put("app",ConstantPara.EXPRESS_CABINT);

        Gson gg=new Gson();
        String json =gg.toJson(map);

        RequestBody body = RequestBody.create(JSON,json);
        OkGo.<LzyResponse<loginModel>>post(Urls.URL_LOGIN)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<loginModel>>(Login1Activity.this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<loginModel>> response) {
                        PrefUtils.setString(Login1Activity.this, "userName", phonenum.getText().toString().trim());
                        if (isRemember) {
                            PrefUtils.setString(Login1Activity.this, "password", password.getText().toString().trim());
                        } else {
                            PrefUtils.setString(Login1Activity.this, "password", "");
                        }


                        Log.e("LoginActivity","onSuccess--------------------");
                        loginModel loginCabModel = response.body().data;
                        PrefUtils.setString(Login1Activity.this, "userId", loginCabModel.getId());
                        BaseApplication.getIntance().setLoginBean(response.body().data);

                        /*if (null != BaseApplication.getIntance().getLoginBean().getPhoneList() && BaseApplication.getIntance().getLoginBean().getPhoneList().size() != 0) {
                            ClientInfoDaoImp.getInstance(Login1Activity.this).deleteAll();
                            for (int i = 0; i < BaseApplication.getIntance().getLoginBean().getPhoneList().size(); i++) {
                                ClientInfoDaoImp.getInstance(Login1Activity.this).AddTelNum(BaseApplication.getIntance().getLoginBean().getPhoneList().get(i));
                            }
                        }*/

//                      Log.e("MainActivity","onSuccess--------------------"+BaseApplication.getIntance().getLoginBean().getId());
//                      Log.e("MainActivity","onSuccess--------------------"+BaseApplication.getIntance().getLoginBean().getMobile());
                        BaseApplication.getIntance().setLogin(true);
                        startActivity(new Intent(Login1Activity.this, MainActivity.class));
//
                        finish();
                    }

                    @Override
                    public void onError(Response<LzyResponse<loginModel>> response) {
                        Log.e("LoginActivity","onError---------------------");
//                      startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        Toast.makeText(getApplicationContext(), getResources().getString(R.string.login_failed), Toast.LENGTH_SHORT).show();


                    }
                });



    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //Activity销毁时，取消网络请求
        OkGo.getInstance().cancelTag(this);


    }

    @Override
    protected void onResume() {
        super.onResume();
        phonenum.setText(PrefUtils.getString(Login1Activity.this, "userName", ""));
        password.setText(PrefUtils.getString(Login1Activity.this, "password", ""));
    }
}
